package com.qezhhnjy.cloud.common.pool;

import com.qezhhnjy.cloud.common.pool.conn.Conn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyangfu - 2020/8/20 15:35
 */
@SpringBootApplication
@Slf4j
// 以下注解用于解决 MXBean already registered with name org.apache.commons.pool2 的bean注入问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class PoolApp implements CommandLineRunner {

    @Resource
    private GenericObjectPool<Conn> connPool;

    public static void main(String[] args) {
        SpringApplication.run(PoolApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        while (!Thread.interrupted()) {
            try {
                Conn conn = connPool.borrowObject();
                log.info(conn.toString());
                log.info(String.valueOf(connPool.getNumActive()));
                TimeUnit.SECONDS.sleep(5);
                connPool.returnObject(conn);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                TimeUnit.SECONDS.sleep(5);
            }
        }
    }
}
